﻿using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEditor;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class PrefabDropdownDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            PrefabDropdownAttribute attribute = (PrefabDropdownAttribute)this.fieldInfo.GetCustomAttribute(typeof(PrefabDropdownAttribute), false);
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(property.displayName);
            var rDropdownBtn = EditorGUILayout.DropdownButton(new GUIContent(property.stringValue), FocusType.Passive);
            var rPrefabBtn = GUILayout.Button("预设");
            EditorGUILayout.EndHorizontal();

            if (rDropdownBtn)
            {
                Rect popupRect = EditorGUI.IndentedRect(position);
                popupRect.x += popupRect.width;
                popupRect.y += popupRect.height;
                popupRect.width = 200;
                var options = attribute.GetPrefabList();
                SearchPopupWindow.Create(popupRect, options, property.stringValue, (x) =>
                {
                    if (property.stringValue != x)
                    {
                        property.stringValue = x;
                        property.serializedObject.ApplyModifiedProperties();
                    }
                });
            }
            if (rPrefabBtn)
            {
                var rPrefabKey = property.stringValue;
                if (!string.IsNullOrEmpty(rPrefabKey))
                {
                    PrefabGraphWindow.Open(attribute.GetPrefabGraphPath(rPrefabKey));
                }
            }
        }
    }

    public abstract class PrefabDropdownAttribute : PropertyAttribute
    {
        public PrefabDropdownAttribute()
        {
        }

        public abstract List<string> GetPrefabList();
        
        public abstract string GetPrefabGraphPath(string prefabKey); 
    }
}